// pages/sell/sell.js
import { Shopcart } from "../../models/shopcart.js"
import { Enum } from "../../utils/enum.js"
var shopcart = new Shopcart("sellLocalShopcart")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopcart:{},
    storageKey: Enum.orderType.recycleOrder
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  _loadData() {
    var data = shopcart.getShopcartDetail(this.data.shopcart.selectedAll)
    this.setData({
      shopcart: data
    })
  },

  onChangeNum(event) {
    var bookID = event.detail.bookID
    var changeType = event.detail.changeType * 1
    var result = shopcart.changeNum(bookID, changeType)
    if (result.ok) {
      this.setData({
        shopcart: result.data
      })
    }
  },

  onDeleteOne(event){
    var bookID = event.detail.bookID
    var selectedAll = this.data.shopcart.selectedAll
    var result = shopcart.deleteOne(bookID, selectedAll)
    if(result.ok){
      this.setData({
        shopcart: result.data
      })
    }
  },

/**
 * book 在  缓存  更新缓存数量
 * book 不在 缓存
 * 数据库中有这本书吗？
 * 无          暂时不收
 * 有   更新缓存
 */
  sellBook() {
    var that = this
    wx.scanCode({
      success: function (res) {
        shopcart.showLoading()
        var isbn = res.result
      // 书本已在缓存
        if (shopcart.checkBookInCartByISBN(isbn)){
          var data = shopcart.getShopcartDetail(that.data.shopcart.selectedAll)
          that.setData({
            shopcart: data
          })
          wx.hideLoading()
        }// 书本不在缓存  去数据库搜索
        else {
          shopcart.checkBookInDB(isbn, (res)=>{
            that.notInLocalStorage(res)
          })
        }
      },
      fail: function (error) {
        console.log(error)
      }
    })
  },
    
  notInLocalStorage(res){
    wx.hideLoading()
    if (shopcart.processRes(res.statusCode)) {
      var item = shopcart.getBaseInfo(res.data, false)
      shopcart.addToCart(item, 1)
      var data = shopcart.getShopcartDetail(this.data.shopcart.selectedAll)
      this.setData({
        shopcart: data
      })
    } 
    else {
      shopcart.toast("此书暂不回收","none")
    }
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this._loadData()
  },

  onSelectAll(event) {
    var data = shopcart.selectAll(!this.data.shopcart.selectedAll)
    this.setData({
      shopcart: data
    })
  },

// 不用购物车的缓存？
// 购物车的缓存只有全部的书 没有selectedBookArray
  makeOrder() {
    wx.setStorageSync(this.data.storageKey, this.data.shopcart)
    wx.navigateTo({
      url: "/pages/order/order?orderType=" + this.data.storageKey + "&shopcartType=" + shopcart.shopcartKey
    })
  },

  onSelect(event) {
    var data = shopcart.changeSelectStatus(event.detail.bookID)
    this.setData({
      shopcart: data
    })
  },

  



})